﻿using AutoMapper;
using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using NPOI.POIFS.Crypt.Dsig;

namespace FarmSmartSleep.Organ.API.Application.SleepInfoCommands.FemaleBeginCommands
{
    public class SeedmaleHandler : IRequestHandler<SeedmaleCommand, Result>
    {
        private readonly IBaseRepository<MaleBegin> maleBeginRepository;
        private readonly IBaseRepository<SleepInfor> sleepinforRep;
        private readonly IMapper mapper;

        public SeedmaleHandler(IBaseRepository<MaleBegin> maleBeginRepository, IMapper mapper)
        {
            this.maleBeginRepository = maleBeginRepository;
            this.mapper = mapper;
        }

        public async Task<Result> Handle(SeedmaleCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.add };
            MaleBegin proBegin = mapper.Map<MaleBegin>(request);
            proBegin.CreateTime = DateTime.Now;

            var list = maleBeginRepository.Add(proBegin);
            if (list > 0)
            {
                //当添加成功时，对种母档案中的栋舍栏位和在场状态进行修改
                var res = sleepinforRep.GetAll().FirstOrDefault(x => x.SleepInforId == request.SleepInforId);
                if (res != null)
                {
                    res.StayStatus = 1;
                    res.RecordcottageId = request.CottagesId;
                    res.FieIdId = request.Field;
                    sleepinforRep.Update(res);
                }
            }
            result.Code = list;
            return result;
        }
    }
}
